from rest_framework.views import exception_handler
from rest_framework.response import Response
from utils.common_logger import logger


def common_exception_handler(exc, context):
    res = exception_handler(exc, context)
    if res:  # 有值：drf的异常，处理了，格式不是咱们想要的
        err = res.data.get('detail') or res.data or '未知错误，请联系系统管理员'
        response = Response({'code': 888, 'msg': '请求异常-drf:%s' % err})
    else:  # django的异常，没有处理，自己处理格式，exc异常对象转成字符串
        response = Response({'code': 999, 'msg': '请求异常-其他:%s' % str(exc)})

    # 记录日志
    request = context.get('request')
    path = request.get_full_path()
    method = request.method
    ip = request.META.get('REMOTE_ADDR')
    user_id = request.user.pk or '未登录用户'
    err = str(exc)
    view = str(context.get('view'))
    logger.error(
        '请求错误：请求地址是：%s，请求方式是：%s，请求用户ip地址是：%s，用户id是：%s，错误是：%s，执行的视图函数是：%s' % (
            path, method, ip, user_id, err, view))
    return response
